import express from 'express';
import { WechatyBuilder,ScanStatus } from 'wechaty';
import { FileBox } from 'file-box';
import qrcode from 'qrcode';
import cors from 'cors';
import http from 'http';
import { setupWebSocket } from './websocket.js';
import { store } from './store.js';
import { authMiddleware } from './middleware/auth.js';
import { errorHandler } from './middleware/error.js';
import { config } from './config/index.js';
import qrTerminal from "qrcode-terminal";

const app = express();
const server = http.createServer(app);
const broadcast = setupWebSocket(server);

// 中间件
app.use(cors());
app.use(express.json());
// app.use(authMiddleware);

// 存储bot实例和登录状态
let bot = null;
let isLoggedIn = false;
let qrCodeUrl = null;


// 定义 memory-card 配置
const MEMORY_CARD_NAME = 'wechat-bot';

// 初始化微信机器人
const initBot = () => {
  bot = WechatyBuilder.build({
    name: MEMORY_CARD_NAME,
    puppet: 'wechaty-puppet-padlocal',
  });

  bot.on('scan', async (qrcode, status) => {
  //  if (status === ScanStatus.Waiting || status === ScanStatus.Timeout) {
      // 在控制台显示二维码
      qrTerminal.generate(qrcode, { small: true })
      const qrCodeUrl = ['https://api.qrserver.com/v1/create-qr-code/?data=', encodeURIComponent(qrcode)].join('')
      console.log('onScan:', qrCodeUrl, ScanStatus[status], status)
    // } else {
    //   console.info('onScan: %s(%s)', ScanStatus[status], status)
    // }
  });

  bot.on('login', (user) => {
    isLoggedIn = true;
    qrCodeUrl = null;
    console.log(`用户 ${user} 登录成功`);
  });

  bot.on('logout', () => {
    isLoggedIn = false;
    console.log('用户登出');
  });

  bot.on('message', async (message) => {
    console.log(`on message:${message.toString()}`)
    try {
      const messageData = {
        id: message.id,
        type: message.type(),
        from: {
          id: message.from()?.id,
          name: message.from()?.name(),
        },
        to: {
          id: message.to()?.id,
          name: message.to()?.name(),
        },
        text: message.text(),
        timestamp: message.date(),
        room: message.room() ? {
          id: message.room().id,
          topic: await message.room().topic(),
        } : null,
      };

      store.addMessage(messageData);
      broadcast(messageData);
    } catch (err) {
      console.error('处理消息时出错:', err);
    }
  });

  return bot;
};

// API路由

// 1. 启动微信
app.get('/api/wechat/start', async (req, res) => {
  try {
    if (!bot) {
      bot = initBot();
      await bot.start();
      res.json({ success: true, message: '微信启动成功' });
    } else {
      res.json({ success: false, message: '微信已经启动' });
    }
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

// 2. 获取登录二维码
app.get('/api/wechat/qrcode', (req, res) => {
  if (!isLoggedIn && qrCodeUrl) {
    res.json({
      success: true,
      qrcode: qrCodeUrl,
      tip: '请使用微信扫描二维码登录'
    });
  } else if (isLoggedIn) {
    res.json({
      success: false,
      message: '已经登录'
    });
  } else {
    res.json({
      success: false,
      message: '二维码未生成或已失效，请重新启动微信机器人'
    });
  }
});

// 3. 发送消息
app.post('/api/wechat/send', async (req, res) => {
  try {
    if (!isLoggedIn) {
      return res.status(401).json({ success: false, message: '未登录' });
    }

    const { type, to, content } = req.body;

    // 获取联系人
    const contact = await bot.Contact.find({ name: to });
    if (!contact) {
      return res.status(404).json({ success: false, message: '联系人未找到' });
    }

    // 根据消息类型发送
    switch(type) {
      case 'text':
        await contact.say(content);
        break;
      case 'image':
        const fileBox = FileBox.fromUrl(content);
        await contact.say(fileBox);
        break;
      default:
        return res.status(400).json({ success: false, message: '不支持的消息类型' });
    }

    res.json({ success: true, message: '发送成功' });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

// 4. 获取登录状态
app.get('/api/wechat/status', (req, res) => {
  res.json({
    success: true,
    isLoggedIn,
    botInitialized: !!bot
  });
});

// 辅助函数



// 1. 获取联系人列表
app.get('/api/wechat/contacts', async (req, res) => {
  try {
    if (!isLoggedIn) {
      return res.status(401).json({ success: false, message: '未登录' });
    }

    const contacts = await bot.Contact.findAll();
    const contactList = contacts.map(contact => ({
      id: contact.id,
      name: contact.name(),
      // alias: await contact.alias(),
      alias:contact.alias(),
      gender: contact.gender(),
      avatar: contact.avatar(),
      isFriend: contact.friend(),
    }));

    res.json({ success: true, contacts: contactList });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

// 2. 获取群列表
app.get('/api/wechat/rooms', async (req, res) => {
  try {
    if (!isLoggedIn) {
      return res.status(401).json({ success: false, message: '未登录' });
    }

    const rooms = await bot.Room.findAll();
    const roomList = await Promise.all(rooms.map(async room => ({
      id: room.id,
      topic: await room.topic(),
      memberCount: (await room.memberAll()).length,
      owner: (await room.owner())?.name(),
      avatar: await room.avatar(),
    })));

    res.json({ success: true, rooms: roomList });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

// 3. 群管理相关接口
// 3.1 获取群成员
app.get('/api/wechat/room/:roomId/members', async (req, res) => {
  try {
    const room = await bot.Room.find({ id: req.params.roomId });
    if (!room) {
      return res.status(404).json({ success: false, message: '群聊不存在' });
    }

    const members = await room.memberAll();
    const memberList = members.map(member => ({
      id: member.id,
      name: member.name(),
      avatar: member.avatar(),
    }));

    res.json({ success: true, members: memberList });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

// 3.2 邀请联系人入群
app.post('/api/wechat/room/:roomId/invite', async (req, res) => {
  try {
    const { contactIds } = req.body;
    const room = await bot.Room.find({ id: req.params.roomId });
    if (!room) {
      return res.status(404).json({ success: false, message: '群聊不存在' });
    }

    const contacts = await Promise.all(
        contactIds.map(id => bot.Contact.find({ id }))
    );
    await room.add(contacts);

    res.json({ success: true, message: '邀请成功' });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

// 3.3 将成员移出群聊
app.delete('/api/wechat/room/:roomId/member/:contactId', async (req, res) => {
  try {
    const room = await bot.Room.find({ id: req.params.roomId });
    if (!room) {
      return res.status(404).json({ success: false, message: '群聊不存在' });
    }

    const contact = await bot.Contact.find({ id: req.params.contactId });
    if (!contact) {
      return res.status(404).json({ success: false, message: '联系人不存在' });
    }

    await room.del(contact);
    res.json({ success: true, message: '移除成功' });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

// 4. 文件传输
// 4.1 发送文件
app.post('/api/wechat/file/send', async (req, res) => {
  try {
    const { to, fileUrl, filename } = req.body;

    const contact = await bot.Contact.find({ name: to });
    if (!contact) {
      return res.status(404).json({ success: false, message: '联系人未找到' });
    }

    const fileBox = FileBox.fromUrl(fileUrl, filename);
    await contact.say(fileBox);

    res.json({ success: true, message: '文件发送成功' });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});

// 5. 消息历史记录
app.get('/api/wechat/messages', (req, res) => {
  try {
    const { limit } = req.query;
    const messages = store.getMessages(parseInt(limit) || 100);
    res.json({ success: true, messages });
  } catch (err) {
    res.status(500).json({ success: false, error: err.message });
  }
});




// 错误处理
app.use(errorHandler);

// 启动服务器
server.listen(config.port, () => {
  console.log(`Server running on port ${config.port}`);
});

